package com.ruoyi.coal.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.coal.common.xss.SQLFilter;
import java.util.Map;
import org.apache.commons.lang.StringUtils;

public class Query<T> {
    public IPage<T> getPage(Map<String, Object> params) {
        return getPage(params, null, false);
    }

    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        long curPage = 1L;
        long limit = 10L;
        if (params.get("page") != null)
            curPage = Long.parseLong((String)params.get("page"));
        if (params.get("limit") != null)
            limit = Long.parseLong((String)params.get("limit"));
        Page<T> page = new Page(curPage, limit);
        params.put("page", page);
        String orderField = SQLFilter.sqlInject((String)params.get("sidx"));
        String order = (String)params.get("order");
        if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) {
            if ("asc".equalsIgnoreCase(order))
                return (IPage<T>)page.addOrder(new OrderItem[] { OrderItem.asc(orderField) });
            return (IPage<T>)page.addOrder(new OrderItem[] { OrderItem.desc(orderField) });
        }
        if (StringUtils.isBlank(defaultOrderField))
            return (IPage<T>)page;
        if (isAsc) {
            page.addOrder(new OrderItem[] { OrderItem.asc(defaultOrderField) });
        } else {
            page.addOrder(new OrderItem[] { OrderItem.desc(defaultOrderField) });
        }
        return (IPage<T>)page;
    }
}

